package net.mikoo.seals.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.charset.Charset;

import org.apache.commons.lang.SerializationException;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.util.Assert;

public class ObjectRedisSerializer implements RedisSerializer<Object> {
    private final Charset charset;

    public ObjectRedisSerializer() {
        this(Charset.forName("UTF8"));
    }

    public ObjectRedisSerializer(Charset charset) {
        Assert.notNull(charset, "");
        this.charset = charset;
    }

    public Object deserialize(byte[] bytes) {
        ByteArrayInputStream bi = null;
        ObjectInputStream oi = null;
        try {
            if (bytes == null) {
                return null;
            }
            bi = new ByteArrayInputStream(bytes);
            oi = new ObjectInputStream(bi);
            Object obj = oi.readObject();
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bi != null) {
                    bi.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (oi != null) {
                    try {
                        oi.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }

    public byte[] serialize(String string) {
        return (string == null ? null : string.getBytes(charset));
    }

    @Override
    public byte[] serialize(Object t)
            throws SerializationException {
        if (t == null) {
            return null;
        }
        byte[] bytes = null;
        ByteArrayOutputStream bo = null;
        ObjectOutputStream oo = null;
        try {
            // object to bytearray
            bo = new ByteArrayOutputStream();
            oo = new ObjectOutputStream(bo);
            oo.writeObject(t);
            bytes = bo.toByteArray();
        } catch (Exception e) {
            System.out.println("translation" + e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                if (bo != null) {
                    try {
                        bo.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } finally {
                if (oo != null) {
                    try {
                        oo.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return bytes;
    }
}
